package com.share.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.share.domain.User;
import com.share.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created By caifan on 2018/6/3
 */
@RestController
@RequestMapping("/rest/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private Registration registration;

    @HystrixCommand(fallbackMethod = "fallbackUser", commandProperties = {@HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"), @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value="7000")},
                                                    threadPoolProperties = {@HystrixProperty(name = "coreSize", value = "15")})
    @RequestMapping(value = "/{id}")
    public ResponseEntity getUserById(@PathVariable("id") Long id) {
        try {
//            Thread.sleep(3000);
            return new ResponseEntity(userService.findById(id), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity(e.getMessage(), HttpStatus.EXPECTATION_FAILED);
        }
    }

    public ResponseEntity saveUser(User user) {
        try {
            userService.saveUser(user);
            return new ResponseEntity("SUCCESS", HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity(e.getMessage(), HttpStatus.EXPECTATION_FAILED);
        }
    }

    public String getIPAndPort() {
        return registration.getHost() + ":" + registration.getPort();
    }

    public ResponseEntity fallbackUser(Long id) {
//        return new ResponseEntity(new User(), HttpStatus.OK);
        throw new RuntimeException("user not exists");
    }
}
